package org.brakepedal.server.util;

import io.netty.buffer.ByteBufAllocator;

import java.io.IOException;
import java.util.Formatter;
import java.util.Locale;

/**
 * Date: 2024/4/8 22:04
 *
 * @author Huanyu Mark
 */
public class ByteLookup {
    private ByteLookup(){}

//    public static final String HEXDIGITSTRING = "0123456789abcdef";

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
    public static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3+2);
        sb.append("[");
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.substring(0,sb.length()-1)+"]";
    }

    public static String toHexString(byte b){
        var unsigned = ((int) b) & 0xff;
        return String.valueOf(HEXDIGITS[unsigned >> 4]) +
                HEXDIGITS[unsigned & 15];
    }
    public static void print(byte b){
        print("Byte: ",b);
    }

    public static void print(String prompt,byte b){
        var unsigned = ((int) b) & 0xff;
        System.out.println(prompt + " " + HEXDIGITS[unsigned >> 4] + HEXDIGITS[unsigned & 15]);
    }

    public static void print(String prompt, byte[] bs) {
        print(prompt,bs,0,bs.length);
    }

    public static void print(String prompt, byte[] bs, int start, int end){
        if(start < 0 || start > end || start > bs.length || end > bs.length) {
           throw new IllegalArgumentException("Invalid range");
        }
        int byteCount = end - start;
        var sb = new StringBuilder(byteCount * 3 + byteCount >> 4 + prompt.length() + 12);
        sb.append(prompt).append(" ");
        for (int i = start; i < end; i++) {
            var b = ((int) bs[i]) & 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
            if(i % 16 == 0) {
                sb.append('\n');
            }
        }
        if(sb.charAt(sb.length()-1) != '\n') {
            sb.append('\n');
        }
        sb.append("Total: ").append(byteCount);
        System.out.println(sb);
    }
}
